<template>
  <ConfigProvider :locale="zhCN">
    <div
      class="
        fixed
        right-0
        top-80
        m-5
        z-8888
        flex
        font-sans
        select-none
        leading-1em
        pointer-events-none
      "
      v-if="appShow"
    >
      <div
        class="bg-white text-gray-800 shadow w-max h-min rounded-2xl"
        p="x-4 y-5"
        m="y-auto r-2"
        transition="opacity duration-300"
        :class="
          show
            ? 'opacity-100 pointer-events-auto'
            : 'opacity-0 pointer-events-none'
        "
      >
        <template v-if="isLogin">
          <MatchFormVue
            v-if="matchMode === 'MATCH_ING'"
            @finish="onMatchIngFinish"
          />
          <MatchRespVue v-else :data="matchResp" />
        </template>

        <LoginFormVue v-else @finish="onLoginSuccessfull" />
      </div>
      <div
        class="
          flex
          w-20
          h-20
          rounded-full
          shadow
          cursor-pointer
          z-9999
          relative
          pointer-events-auto
        "
        bg="teal-600 hover:teal-700"
        @click="onToggle"
      >
        <img :src="LogoSrc" alt="" class="w-full h-full" />
      </div>
    </div>
  </ConfigProvider>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import { useToggle } from '@vueuse/core';
import 'virtual:windi.css';
import { storageToken } from '~/logic/storage';
import MatchFormVue from './components/MatchForm.vue';
import LoginFormVue from './components/LoginForm.vue';
import MatchRespVue from './components/MatchResp.vue';
import { ConfigProvider } from 'ant-design-vue';
import LogoSrc from '~/assets/icon-288.png';
import { sendMessage } from 'webext-bridge';
import { EXT_GET_USER_TOKEN } from '~/events';

const [show, toggle] = useToggle(false);
const [appShow, toggleAppShow] = useToggle(false);
const isLogin = ref(false);
const matchResp = ref();
const matchMode = ref<'MATCH_ING' | 'MATCH_END'>('MATCH_ING');
onMounted(() => {
  const html = document.documentElement;
  html.style.fontSize = `${12}px`;
  setTimeout(() => {
    toggleAppShow(true);
  }, 1000);
});

async function checkBackgroundHasToken() {
  try {
    const token = await sendMessage(EXT_GET_USER_TOKEN, {});
    if (token) {
      storageToken.value = token as string;
      isLogin.value = true;
    } else {
      storageToken.value = null;
      isLogin.value = false;
    }
  } catch (error) {
    storageToken.value = null;
    isLogin.value = false;
  }
}

function onMatchIngFinish(respData: any) {
  matchResp.value = respData;
}

function onLoginSuccessfull() {
  checkBackgroundHasToken();
}

function onToggle() {
  toggle();
}

checkBackgroundHasToken();
</script>
